package monster.com.cvh.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import monster.com.cvh.R;
import monster.com.cvh.activity.base.PermissionActivity;
import monster.com.cvh.adapter.LookedAdapter;
import monster.com.cvh.bean.CollectionBean;
import monster.com.cvh.bean.PostBean;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.RecyclerViewDivider;
import monster.com.cvh.util.SPUtils;
import monster.com.cvh.util.StatusBarUtil;
import okhttp3.Call;
import okhttp3.Response;

/**
 * @author: monster
 * @data: 2018/3/29
 * @function: 我浏览过的界面
 */
public class LookedActivity extends PermissionActivity {
    @BindView(R.id.iv_collection_back)
    ImageView ivCollectionBack;
    @BindView(R.id.tv_colletion_title_bar)
    TextView tvColletionTitleBar;
    @BindView(R.id.tv_title_bar_delete)
    TextView tvTitleBarDelete;
    @BindView(R.id.rl_activity_looked)
    RecyclerView rlActivityLooked;
    @BindView(R.id.rf_activity_looked)
    SmartRefreshLayout rfActivityLooked;
    private List<CollectionBean.DataBean> mDatas = new ArrayList<>();
    private int page = 1;
    private List<CollectionBean.DataBean> data;
    private boolean isFirstIn = true;
    private LookedAdapter lookedAdapter;
    private View empty;

    @Override
    protected int getContentViewResId() {
        return R.layout.activity_looked;
    }

    @Override
    protected void initEvent() {
        //修改状态栏颜色
        StatusBarUtil.setStatusBarLightMode(LookedActivity.this, Color.WHITE);
        tvColletionTitleBar.setText("我浏览过的");
    }

    private void refreshlayout(RefreshLayout refreshlayout, final boolean b) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (b) {
                    if (mDatas.size() > 0) {
                        mDatas.clear();
                        page = 1;
                    }
                    getLook(page);
                    rlActivityLooked.setAdapter(lookedAdapter);
                    rfActivityLooked.finishRefresh();
                    page = 2;

                } else {
                    getLook(page);
                    rfActivityLooked.finishLoadmore();
                    page++;
                }
            }
        }, 2000);
    }

    /**
     * 获取数据
     * @param pageNum 页数
     */
    private void getLook(final int pageNum) {
        OkGo.get(MyConstant.GET_BROWSE_HISTRY).params("token", SPUtils.getString(LookedActivity.this, "token", ""))
                .params("page_index", pageNum).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                final Gson gson = new Gson();
                CollectionBean collectionBean = gson.fromJson(s, CollectionBean.class);
                switch (collectionBean.getCode()) {
                    case 1:
                        data = collectionBean.getData();
                        if (data != null && data.size() > 0) {
                            lookedAdapter.addData(data);
                            /**
                             * 删除一条评论
                             */
                            lookedAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
                                @Override
                                public boolean onItemLongClick(BaseQuickAdapter adapter, View view, final int position) {
                                    new AlertDialog.Builder(LookedActivity.this).setTitle("温馨提示").setMessage("确定要删除本条记录吗？").setCancelable(false)
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialogInterface, int i) {
                                                    //确认
                                                    Log.e("article_id", "onItemLongClick: "+String.valueOf(mDatas.get(position).getArticle_id()) );
                                                    OkGo.<String>delete(MyConstant.DELETE_BROWSE_HISTRY).params("token",SPUtils.getString(LookedActivity.this,"token",""))
                                                            .params("article_id", String.valueOf(mDatas.get(position).getArticle_id())).execute(new StringCallback() {
                                                        @Override
                                                        public void onSuccess(String s, Call call, Response response) {
                                                            PostBean bean = gson.fromJson(s, PostBean.class);
                                                            switch (bean.getCode()){
                                                                case 1:
                                                                    lookedAdapter.remove(position);
                                                                    lookedAdapter.notifyDataSetChanged();
                                                                    break;
                                                            }
                                                        }
                                                    });
                                                }
                                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            //取消操作
                                        }
                                    }).show();
                                    return false;
                                }
                            });

                            /**
                             * 跳入新闻详情
                             */
                            lookedAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                    int id = mDatas.get(position).getArticle_id();
                                    Intent intent = new Intent(LookedActivity.this, NewsDetailsActivity.class);
                                    intent.putExtra("id", id);
//                                    intent.putExtra("collect", article);
                                    intent.putExtra("isCollect", mDatas.get(position).isIs_collected());
                                    intent.putExtra("reply",mDatas.get(position).getComment_count());
                                    startActivity(intent);
                                }
                            });
                        }else {
                            lookedAdapter.setEmptyView(empty);
                            showToastShort("已无更多数据");
                        }
                        break;
                    case -1002:
                    case -1003:
                    case -1004:
                        showToastShort("获取失败");
                        break;
                }
            }
        });
    }

    @Override
    protected void initData() {
        empty = LayoutInflater.from(this).inflate(R.layout.item_empty,null);
        ImageView ivEmpty = empty.findViewById(R.id.iv_empty);
        ivEmpty.setImageResource(R.mipmap.mine_read_nothing);
        TextView tv = empty.findViewById(R.id.tv_empty);
        tv.setText("暂无数据，请到资讯模块浏览");
        if (isFirstIn) {
            rfActivityLooked.autoRefresh(100);
        }
        rlActivityLooked.setLayoutManager(new LinearLayoutManager(this));
        rlActivityLooked.addItemDecoration(new RecyclerViewDivider(this, LinearLayoutManager.HORIZONTAL, 2, Color.parseColor("#cfcfcf")));
        lookedAdapter = new LookedAdapter(R.layout.item_collection, mDatas);
        rfActivityLooked.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refreshlayout(refreshlayout, false);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout(refreshlayout, true);
            }
        });

    }

    /**
     * 回退
     */
    @OnClick(R.id.iv_collection_back)
    public void onIvCollectionBackClicked() {
        finish();
    }

    /**
     *
     */
    @OnClick(R.id.tv_title_bar_delete)
    public void onTvTitleBarDeleteClicked() {
        new AlertDialog.Builder(this).setMessage("是否确认清空？").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //确认
                OkGo.<String>delete(MyConstant.DELETE_BROWSE_HISTRY).params("token",SPUtils.getString(LookedActivity.this,"token",""))
                        .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        PostBean bean = gson.fromJson(s, PostBean.class);
                        switch (bean.getCode()){
                            case 1:
                                mDatas.clear();
                                lookedAdapter.setEmptyView(empty);
                                lookedAdapter.notifyDataSetChanged();
                                showToastLong("清空成功");
                                break;
                        }
                    }
                });
            }
        }).setCancelable(false).
                setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).show();
    }

}
